package delete;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreFailureException;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class MultipleDeleteServlet extends HttpServlet {
	
	private static BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	private static DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, BlobstoreFailureException {
		//String[] keys = new String[100];
		String keys = req.getParameter("selectListKeys[]"); //getting the list of keys
		if (!keys.equals(null)) {
			String[] keysArray = keys.split(",");
			for(int i=0; i < keysArray.length; i++)
			{
				Key entityKey = KeyFactory.stringToKey(keysArray[i]);
				Entity file;
				
				try {
					file = datastore.get(entityKey);
					BlobKey blobKey = (BlobKey) file.getProperty("blobKey");
					deleteMediaFile(file, blobKey);
				} catch (EntityNotFoundException e) {
					// delete failed, redirect to a different page
				} catch (BlobstoreFailureException e1) {
					resp.sendRedirect(req.getHeader("referer"));
				}
			}
		}
		// redirect to a confirmation page
		resp.sendRedirect(req.getHeader("referer"));
	}
	
	public static void deleteMediaFile(Entity mediaInfo, BlobKey blobKey) {
		// delete the object from the blobstore
		blobstoreService.delete(blobKey);
		// delete the entity in the datastore
		datastore.delete(mediaInfo.getKey());
	}
}
